package com.training.controller;

import com.training.entity.Information;
import com.training.entity.InformationComment;
import com.training.entity.User;
import com.training.service.InformationCommentService;
import com.training.service.InformationService;
import com.training.service.TeacherService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/info")
public class InformationController {

    private final InformationService infoService;
    private final InformationCommentService commentService;
    private final TeacherService teacherService;

    public InformationController(InformationService infoService, InformationCommentService commentService, TeacherService teacherService) {
        this.infoService = infoService;
        this.commentService = commentService;
        this.teacherService = teacherService;
    }

    // 教师管理自己的资讯
    @GetMapping("/manage")
    public String manageInfo(Model model, HttpSession session, @RequestParam(required = false) String keyword) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null || !"TEACHER".equals(user.getRole())) return "redirect:/login";

        Long teacherId = teacherService.getTeacherIdByUserId(user.getId());
        List<Information> infoList = infoService.getInformationByTeacher(teacherId, keyword);
        model.addAttribute("infoList", infoList);
        return "info-manage";
    }

    // 显示创建页面
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("information", new Information());
        return "info-add";
    }

    // 处理创建请求
    @PostMapping("/add")
    public String addInfo(@ModelAttribute Information information, @RequestParam("imageFile") MultipartFile imageFile, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) return "redirect:/login";

        Long teacherId = teacherService.getTeacherIdByUserId(user.getId());
        information.setTeaId(teacherId);

        try {
            infoService.createInformation(information, imageFile);
            redirectAttributes.addFlashAttribute("successMessage", "资讯发布成功！");
        } catch (IOException e) {
            redirectAttributes.addFlashAttribute("errorMessage", "图片上传失败！");
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/info/manage";
    }

    // 显示编辑页面
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        model.addAttribute("information", infoService.getInformationById(id));
        return "info-add"; // 复用创建页面作为编辑页面
    }

    // 处理编辑请求
    @PostMapping("/edit/{id}")
    public String editInfo(@PathVariable Long id, @ModelAttribute Information information, @RequestParam("imageFile") MultipartFile imageFile, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) return "redirect:/login";

        Long teacherId = teacherService.getTeacherIdByUserId(user.getId());
        information.setId(id);
        information.setTeaId(teacherId);

        try {
            infoService.updateInformation(information, imageFile);
            redirectAttributes.addFlashAttribute("successMessage", "资讯更新成功！");
        } catch (IOException e) {
            redirectAttributes.addFlashAttribute("errorMessage", "图片上传失败！");
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/info/manage";
    }

    // 处理删除请求
    @PostMapping("/delete/{id}")
    public String deleteInfo(@PathVariable Long id, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) return "redirect:/login";

        Long teacherId = teacherService.getTeacherIdByUserId(user.getId());
        infoService.deleteInformation(id, teacherId);
        redirectAttributes.addFlashAttribute("successMessage", "资讯删除成功！");
        return "redirect:/info/manage";
    }

    // 所有用户浏览资讯列表
    @GetMapping("/browse")
    public String browseInfo(Model model, @RequestParam(required = false) String keyword) {
        List<Information> infoList = infoService.getAllInformation(keyword);
        model.addAttribute("infoList", infoList);
        return "info-browse";
    }

    // 查看单篇资讯详情和评论
    @GetMapping("/detail/{id}")
    public String detailInfo(@PathVariable Long id, Model model) {
        Information info = infoService.getInformationById(id);
        List<InformationComment> comments = commentService.getCommentsByInfoId(id);

        model.addAttribute("info", info);
        model.addAttribute("comments", comments);
        model.addAttribute("newComment", new InformationComment());
        return "info-detail";
    }

    // 提交资讯评论
    @PostMapping("/detail/{id}/comment")
    public String addInfoComment(@PathVariable Long id, @ModelAttribute InformationComment newComment, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) return "redirect:/login";

        newComment.setInfoId(id);
        newComment.setUserId(user.getId());

        try {
            commentService.addComment(newComment);
            redirectAttributes.addFlashAttribute("successMessage", "评论发表成功！");
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/info/detail/" + id;
    }
}